package org.benxiong.iplay.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.StatFs;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;

import com.polites.android.GestureImageView;

public class ImageUtil {
	public static final int	COMPRESS_LEVEL_1	= 200 * 200;
	public static final int	COMPRESS_LEVEL_2	= 320 * 480;
	public static final int	COMPRESS_LEVEL_3	= 480 * 800;

	public static final int	AVATOR_WIDTH		= 90;
	public static final int	AVATOR_HEIGHT		= 90;
	
	public static final int PHOTO_WIDTH = 250;

	public static byte[] bitmapToBytes(Bitmap bitmap) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}

	public static boolean isSDMounted() {
		if (Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			return true;
		}

		return false;
	}

	public static boolean isSpaceEnough(int fileSize) {
		String exDir = Environment.getExternalStorageDirectory().getPath();
		StatFs fs = new StatFs(exDir);
		int leftSize = fs.getAvailableBlocks() * fs.getBlockSize();

		if (fileSize > leftSize) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * copy image file as avator
	 * 
	 * @param srcFile
	 * @return
	 */
	public static String saveToLocal(File srcFile) {
		if (srcFile == null) {
			return null;
		}

		String imgDir = GlobalVar.appContext.getFilesDir().getPath();

		File folder = new File(imgDir + "/iplay");
		if (!folder.exists()) {
			folder.mkdir();
		}

		File file = new File(folder, "myAvator.jpg");

		// remove old avator
		if (file.exists()) {
			file.delete();
		}

		InputStream inStream = null;
		try {
			inStream = new FileInputStream(srcFile);
			FileOutputStream fs = new FileOutputStream(file);
			byte[] buffer = new byte[1024];
			int length;
			while ((length = inStream.read(buffer)) != -1) {
				fs.write(buffer, 0, length);
			}

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (inStream != null) {
					inStream.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return file.getPath();

	}

	public static File getAvatorCache() {
		String imgDir = GlobalVar.appContext.getFilesDir().getPath();
		File folder = new File(imgDir + "/iplay");
		File file = new File(folder, "myAvator.jpg");
		return file;
	}

	public static Bitmap getAvatorBitmap() {
		String imgDir = GlobalVar.appContext.getFilesDir().getPath();
		File folder = new File(imgDir + "/iplay");
		File file = new File(folder, "myAvator.jpg");
		if (file.exists()) {
			return getBitmapFromFile(file, AVATOR_WIDTH, AVATOR_HEIGHT);
		}

		return null;
	}

	// public String saveToMemory(byte[] bytes) {
	// Environment.getDataDirectory()
	// }

	public static boolean isBitmapsEqual(Bitmap b1, Bitmap b2) {
		if (b1 != b2) {
			// æ¯”è¾ƒæ˜¯å�¦æœ‰ä¸€ä¸ªä¸ºnull
			if ((b1 == null && b2 != null) || (b1 != null && b2 == null)) {
				return false;
			}

			// æ¯”è¾ƒå¤§å°�
			// if (b1.get != b2.getByteCount()) {
			// return false;
			// }

			// æ¯”è¾ƒé•¿é«˜
			if (b1.getHeight() != b2.getHeight()
					|| b1.getWidth() != b2.getWidth()) {
				return false;
			}

			// æ¯”è¾ƒåƒ�ç´ 
			int width = b1.getWidth();
			int height = b1.getHeight();
			for (int i = 0; i < width; i++) {
				for (int j = 0; j < height; j++) {
					if (b1.getPixel(i, j) != b2.getPixel(i, j)) {
						return false;
					}
				}
			}

			return true;
		} else {
			// reference is the same , bitmaps are same
			return true;
		}
	}

	public static Bitmap getBitmapFromFile(File dst, int width, int height) {
		if (null != dst && dst.exists()) {
			BitmapFactory.Options opts = null;
			if (width > 0 && height > 0) {
				opts = new BitmapFactory.Options();
				opts.inJustDecodeBounds = true;
				BitmapFactory.decodeFile(dst.getPath(), opts);
				// è®¡ç®—å›¾ç‰‡ç¼©æ”¾æ¯”ä¾‹
				final int minSideLength = Math.min(width, height);
				opts.inSampleSize = computeSampleSize(opts, minSideLength,
						width * height);
				opts.inJustDecodeBounds = false;
				LogX.print("inSampleSize="+opts.inSampleSize);
			}
			try {
				return BitmapFactory.decodeFile(dst.getPath(), opts);
			} catch (OutOfMemoryError e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public static int computeSampleSize(BitmapFactory.Options options,
			int minSideLength, int maxNumOfPixels) {
		int initialSize = computeInitialSampleSize(options, minSideLength,
				maxNumOfPixels);

		int roundedSize;
		if (initialSize <= 8) {
			roundedSize = 1;
			while (roundedSize < initialSize) {
				roundedSize <<= 1;
			}
		} else {
			roundedSize = (initialSize + 7) / 8 * 8;
		}

		return roundedSize;
	}

	private static int computeInitialSampleSize(BitmapFactory.Options options,
			int minSideLength, int maxNumOfPixels) {
		double w = options.outWidth;
		double h = options.outHeight;

		int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
				.sqrt(w * h / maxNumOfPixels));
		int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
				Math.floor(w / minSideLength), Math.floor(h / minSideLength));

		if (upperBound < lowerBound) {
			// return the larger one when there is no overlapping zone.
			return lowerBound;
		}

		if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
			return 1;
		} else if (minSideLength == -1) {
			return lowerBound;
		} else {
			return upperBound;
		}
	}

	public static ByteArrayInputStream getResizedInputStreamFromFile(String picturePath, int maxWidth) {
		File file = new File(picturePath);

		Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
		if (myBitmap.getWidth() > maxWidth || myBitmap.getHeight() > maxWidth) {
			double width = maxWidth;
			double height = maxWidth;
			double scale = myBitmap.getWidth() / (double) maxWidth;
			// TODO: resize
			if (myBitmap.getWidth() > myBitmap.getHeight()) {
				scale = myBitmap.getHeight() / (double) maxWidth;
				height = scale * myBitmap.getHeight();
			} else {
				width = scale * myBitmap.getWidth();
			}

			myBitmap = Bitmap.createScaledBitmap(myBitmap, (int) width, (int) height, true);
		}

		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		myBitmap.compress(CompressFormat.JPEG, 75, bos);
		byte[] bitmapdata = bos.toByteArray();
		final ByteArrayInputStream bs = new ByteArrayInputStream(bitmapdata);
		return bs;
	}

	public static void showImageViewInDialog(final GestureImageView imgV, Context context) {
		final Context _context = context;
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		final AlertDialog dialog = builder.setView(imgV).create();
		WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
		lp.copyFrom(dialog.getWindow().getAttributes());
		lp.width = WindowManager.LayoutParams.MATCH_PARENT;
		lp.height = WindowManager.LayoutParams.MATCH_PARENT;

		dialog.show();
		dialog.getWindow().setAttributes(lp);

		imgV.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
	}
}
